from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from database.database import get_db
from core.base.api_mode import ApiResponse, api_success
from modules.system.schemas.role_schemas import RoleCreate, RoleUpdate, RolePermissionsUpdateRequest
from modules.system.params.role_params import RoleQuery
from modules.system.vos.role_vo import RoleResponse, RoleListResponse, RolePermissionsResponse
from modules.system.services.role_service import RoleService
from core.pagination import DependsPagination

router = APIRouter()


@router.post("/create", response_model=ApiResponse[RoleResponse], summary="创建角色")
async def create_role(payload: RoleCreate, db: AsyncSession = Depends(get_db)):
    role = await RoleService.create_role(db, payload)
    return api_success(RoleResponse.model_validate(role), msg="创建成功")


@router.post(
    "/list", 
    response_model=ApiResponse[RoleListResponse], 
    summary="获取角色列表",
    dependencies=[DependsPagination]
    )
async def list_roles(query_params: RoleQuery, db: AsyncSession = Depends(get_db)):
    result = await RoleService.get_roles_with_pagination(db, query_params)
    return api_success(data=result,msg="获取成功")


@router.put("/{role_id}", response_model=ApiResponse[RoleResponse], summary="更新角色")
async def update_role(role_id: int, payload: RoleUpdate, db: AsyncSession = Depends(get_db)):
    role = await RoleService.update_role(db, role_id, payload)
    return api_success(RoleResponse.model_validate(role), msg="更新成功")


@router.delete("/{role_id}", response_model=ApiResponse[dict], summary="删除角色")
async def delete_role(role_id: int, db: AsyncSession = Depends(get_db)):
    await RoleService.delete_role(db, role_id)
    return api_success({"message": f"角色ID {role_id} 删除成功"}, msg="删除成功")


@router.get("/{role_id}/permissions", response_model=ApiResponse[RolePermissionsResponse], summary="获取角色权限")
async def get_role_permissions(role_id: int, db: AsyncSession = Depends(get_db)):
    # 校验角色是否存在
    role = await RoleService.get_role_by_id(db, role_id)
    if not role:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="角色不存在")
    ids = await RoleService.get_role_permissions(db, role_id)
    return api_success(RolePermissionsResponse(role_id=role_id, permission_ids=ids), msg="获取成功")


@router.put("/{role_id}/permissions", response_model=ApiResponse[RolePermissionsResponse], summary="更新角色权限")
async def update_role_permissions(role_id: int, payload: RolePermissionsUpdateRequest, db: AsyncSession = Depends(get_db)):
    role = await RoleService.get_role_by_id(db, role_id)
    if not role:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="角色不存在")
    ids = await RoleService.update_role_permissions(db, role_id, payload.permission_ids)
    return api_success(RolePermissionsResponse(role_id=role_id, permission_ids=ids), msg="更新成功")